# -*- coding: utf-8 -*-
# @Time    : 2025/6/28 13:56
# @Author  : Alvin
# @File    : JlYuYueImpl.py
# @Des     :
import json
import logging
import traceback
from concurrent.futures import ThreadPoolExecutor

import requests

from constants import Constants
from handler.BaseLogisticsImpl import BaseLogisticsImpl
from utils import CommonUtil, CheUtil


class JlYuYueImpl(BaseLogisticsImpl):

    def __init__(self):
        super(JlYuYueImpl, self).__init__()
        self.max_workers = 2
        self.log_text = "同步单预约任务"
        self.need_update_list = []

    def start_handle_yuyue_task(self, batch_index, db_data_list):
        """
        开始处理同步单预约任务
        :param batch_index: 当前任务批次
        :param db_data_list:
        :return:
        """
        try:
            is_login = self.check_user_is_logined()
            if not is_login:
                logging.error("用户登录失败，请检查登录数据是否异常")
                return
            with ThreadPoolExecutor(max_workers=self.max_workers) as pool:
                for item in db_data_list:
                    pool.submit(self.handle_yuyue_task, item)
            logging.info(f"第【{batch_index}】数据跑完了，共需更新:{len(self.need_update_list)}条数据")
            self.db_util.update_sync_order_yuyue_info(self.need_update_list)
        except Exception as ex:
            logging.error(f"【start_handle_dy_update_task】异常:{str(ex)}")
            logging.error(f"【start_handle_dy_update_task】异常2:%s", traceback.format_exc())

    def handle_yuyue_task(self, dbItem):
        mail_no_self = dbItem.get("mailNo_self")
        row_id = dbItem.get("id")
        url = "https://app.lqfast.com/AppApis.ashx"
        param = {
            "companyid": "78210",
            "proc": "USP_SF_ORDER_RESERVE_APP",
            "method": "Query",
            "pars": [
                {
                    "LoginWeb": "",
                    "sfman": "优斯雅通达",  # 经办人
                    "khyySjd": "全天",
                    "PublicIP": "",
                    "LoginSite": "",
                    "mac": "android",
                    "content": Constants.sb_default_content,
                    "LoginUserID": Constants.sb_phone,
                    "LoginUserName": Constants.sb_name,
                    "unit": mail_no_self,
                    "LocalIP": "",
                    "billdate": CommonUtil.get_current_format_time(),
                    "childcomid": Constants.logistics_code
                }
            ],
            "username": Constants.sb_phone,
            "token": self.app_token
        }
        p = {
            "pars": json.dumps(param)
        }
        headers = CheUtil.get_app_header()
        resp_json = requests.post(url, data=p, headers=headers).json()
        logging.info(f"【{mail_no_self}】预约结果：{resp_json}")
        if resp_json['result'] == '0':
            self.need_update_list.append({
                "id": row_id,
                "statusStr": "已预约",
                "statusCode": "已预约",
                "logisticsInfo": Constants.sb_default_content,
                "updateTime": CommonUtil.get_current_format_time()
            })
        else:
            logging.error(f"【{mail_no_self}】预约失败，接口响应：{resp_json}")
